package com.vCamera.ui.record;

import java.util.ArrayList;

import android.annotation.TargetApi;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnInfoListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.huiyin.AppContext;
import com.huiyin.R;
import com.huiyin.UIHelper;
import com.huiyin.api.CustomResponseHandler;
import com.huiyin.api.RequstClient;
import com.huiyin.bean.MomentsCircleItem;
import com.huiyin.bean.MomentsCircleListBean;
import com.huiyin.bean.MomentsPublishParams;
import com.huiyin.ui.MainActivity;
import com.huiyin.ui.moments.MomentsShowPictureActivity;
import com.huiyin.ui.moments.view.MomentsCircleListDialog;
import com.huiyin.ui.moments.view.MomentsCircleListDialog.SelectCircleListener;
import com.huiyin.utils.AppManager;
import com.huiyin.utils.JSONParseUtils;
import com.huiyin.utils.UPYunUploadUtil;
import com.huiyin.utils.UPYunUploadUtil.UploadListener;
import com.huiyin.wight.Tip;
import com.vCamera.ui.BaseActivity;
import com.vCamera.ui.widget.SurfaceVideoView;
import com.vCamera.util.Constant;
import com.yixia.weibo.sdk.util.DeviceUtils;
import com.yixia.weibo.sdk.util.StringUtils;

/**
 * 通用单独播放界面
 * 
 * @author tangjun
 *
 */
public class VideoPlayerActivity extends BaseActivity implements SurfaceVideoView.OnPlayStateListener, OnErrorListener, OnPreparedListener, OnClickListener, OnCompletionListener, OnInfoListener {

	protected static final String TAG = "VideoPlayerActivity";
	
	/** 播放控件 */
	private SurfaceVideoView mVideoView;
	/** 暂停按钮 */
	private View mPlayerStatus;
	private View mLoading;

	/** 播放路径 */
	private String mPath;
	/** 视频截图路径 */
	private String mCoverPath;
	
	/** 是否需要回复播放 */
	private boolean mNeedResume;
	
	/**标题输入框**/
	private EditText mTitleEdt;
	
	/**内容输入框**/
	private EditText mContentEdt;
	
	/**选择圈子布局**/
	private RelativeLayout mSelectCircleLayout;
	
	/** 选择圈子信息 **/
	private TextView mSelectCircleTv;
	
	/**发布**/
	private Button mPublishBtn;
	
	/** 选择的圈子ID **/
	private String selectCircleId = "";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// 防止锁屏
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

		mPath = getIntent().getStringExtra(Constant.RECORD_VIDEO_PATH);
		mCoverPath = getIntent().getStringExtra(Constant.RECORD_VIDEO_CAPTURE);
		if (StringUtils.isEmpty(mPath)) {
			finish();
			return;
		}

		setContentView(R.layout.activity_video_player);
		mVideoView = (SurfaceVideoView) findViewById(R.id.videoview);
		mPlayerStatus = findViewById(R.id.play_status);
		mLoading = findViewById(R.id.loading);

		mVideoView.setOnPreparedListener(this);
		mVideoView.setOnPlayStateListener(this);
		mVideoView.setOnErrorListener(this);
		mVideoView.setOnClickListener(this);
		mVideoView.setOnInfoListener(this);
		mVideoView.setOnCompletionListener(this);

		mVideoView.getLayoutParams().height = DeviceUtils.getScreenWidth(this);

		findViewById(R.id.root).setOnClickListener(this);
		mVideoView.setVideoPath(mPath);
		
		//发布信息
		mTitleEdt = (EditText) findViewById(R.id.edt_title);
		mContentEdt = (EditText) findViewById(R.id.edt_content); 
		mSelectCircleLayout = (RelativeLayout) findViewById(R.id.rl_select_circle);
		mSelectCircleTv = (TextView) findViewById(R.id.tv_circle_select);
		mPublishBtn = (Button) findViewById(R.id.btn_publish);
		
		mSelectCircleLayout.setOnClickListener(this);
		mPublishBtn.setOnClickListener(this);
	}

	@Override
	public void onResume() {
		super.onResume();
		if (mVideoView != null && mNeedResume) {
			mNeedResume = false;
			if (mVideoView.isRelease())
				mVideoView.reOpen();
			else
				mVideoView.start();
		}
	}

	@Override
	public void onPause() {
		super.onPause();
		if (mVideoView != null) {
			if (mVideoView.isPlaying()) {
				mNeedResume = true;
				mVideoView.pause();
			}
		}
	}

	@Override
	protected void onDestroy() {
		if (mVideoView != null) {
			mVideoView.release();
			mVideoView = null;
		}
		super.onDestroy();
	}

	@Override
	public void onPrepared(MediaPlayer mp) {
		mVideoView.setVolume(SurfaceVideoView.getSystemVolumn(this));
		mVideoView.start();
//		new Handler().postDelayed(new Runnable() {
//
//			@SuppressWarnings("deprecation")
//			@Override
//			public void run() {
//				if (DeviceUtils.hasJellyBean()) {
//					mVideoView.setBackground(null);
//				} else {
//					mVideoView.setBackgroundDrawable(null);
//				}
//			}
//		}, 300);
		mLoading.setVisibility(View.GONE);
	}

	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		switch (event.getKeyCode()) {//跟随系统音量走
		case KeyEvent.KEYCODE_VOLUME_DOWN:
		case KeyEvent.KEYCODE_VOLUME_UP:
			mVideoView.dispatchKeyEvent(this, event);
			break;
		}
		return super.dispatchKeyEvent(event);
	}

	@Override
	public void onStateChanged(boolean isPlaying) {
		mPlayerStatus.setVisibility(isPlaying ? View.GONE : View.VISIBLE);
	}

	@Override
	public boolean onError(MediaPlayer mp, int what, int extra) {
		if (!isFinishing()) {
			//播放失败
		}
		finish();
		return false;
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.root:
			//finish();
			break;
		case R.id.videoview:
			if (mVideoView.isPlaying())
				mVideoView.pause();
			else
				mVideoView.start();
			break;
		// 发布
		case R.id.btn_publish:
			if(check()) {
			   uploadVideo();
			}
			break;
		// 选择圈子
		case R.id.rl_select_circle:
			requestCircleList();
			break;
		default:
			break;
		}
	}

	@Override
	public void onCompletion(MediaPlayer mp) {
		if (!isFinishing())
			mVideoView.reOpen();
	}

	@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
  @Override
	public boolean onInfo(MediaPlayer mp, int what, int extra) {
		switch (what) {
		case MediaPlayer.MEDIA_INFO_BAD_INTERLEAVING:
			//音频和视频数据不正确
			break;
		case MediaPlayer.MEDIA_INFO_BUFFERING_START:
			if (!isFinishing())
				mVideoView.pause();
			break;
		case MediaPlayer.MEDIA_INFO_BUFFERING_END:
			if (!isFinishing())
				mVideoView.start();
			break;
		case MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START:
			if (DeviceUtils.hasJellyBean()) {
				mVideoView.setBackground(null);
			} else {
				mVideoView.setBackgroundDrawable(null);
			}
			break;
		}
		return false;
	}
	
	/**
	 * 上传视频
	 */
	private void uploadVideo() {
		
		Tip.showLoadDialog(this, getString(R.string.loading));
		UPYunUploadUtil mUploadUtil = new UPYunUploadUtil(this);
		mUploadUtil.uploadFile(mPath, new UploadListener() {
			
			@Override
			public void onSuccess(String videoBackUrl) {
				Log.d(TAG, "uploadPictures onSuccess　: videoBackUrl = " + videoBackUrl);
				uploadVideoThumb(videoBackUrl);
			}
			
			@Override
			public void onFail() {
				Tip.colesLoadDialog();
				UIHelper.showToast("上传图片失败");
				return;
			}
		});
	}
	
	/**
	 * 上传略所图
	 */
	private void uploadVideoThumb(final String videoBackUrl) {
		UPYunUploadUtil mUploadUtil = new UPYunUploadUtil(this);
		mUploadUtil.uploadFile(mCoverPath, new UploadListener() {
			
			@Override
			public void onSuccess(String thumbBackUrl) {
				Log.d(TAG, "uploadPictures onSuccess　: thumbBackUrl = " + thumbBackUrl);
				Tip.colesLoadDialog();
				publishRequest(videoBackUrl, thumbBackUrl);
			}
			
			@Override
			public void onFail() {
				Tip.colesLoadDialog();
				UIHelper.showToast("上传图片失败");
				return;
			}
		});
	}
	
	 /**
     * 发布请求
     */
	private void publishRequest(String videoBackUrl, String thumbBackUrl) {
		
		MomentsPublishParams params = new MomentsPublishParams();
		params.setType("3");//秀视频
		params.setTitle(mTitleEdt.getText().toString().trim());
		params.setContent(mContentEdt.getText().toString().trim());
		params.setShow_file(videoBackUrl);
		params.setVideo_img(thumbBackUrl);
		params.setSpotlight_circle_id(selectCircleId);
		params.setUser_id(AppContext.getInstance().userId);
		params.setOrigin("3");

		RequstClient.showPublish(params, new CustomResponseHandler(this) {
			@Override
			public void onSuccess(String content) {
				super.onSuccess(content);
				
				int type = JSONParseUtils.getInt(content, "type");
				String msg = JSONParseUtils.getString(content, "msg");
				UIHelper.showToast(msg);
				// 成功
				if(type == 1) {
					Intent intent = new Intent();
					AppContext.MAIN_TASK = AppContext.MOMENTS;
					intent.setClass(VideoPlayerActivity.this, MainActivity.class);
					intent.putExtra(MainActivity.IS_REFRESH_MOMENTS, true);
					intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
					startActivity(intent);
				}
				
				
			}
		});
	
	}
	
	/**
	 * 获取圈子列表
	 */
	private void requestCircleList() {
		RequstClient.circleList(new CustomResponseHandler(this) {
			@Override
			public void onSuccess(String content) {
				super.onSuccess(content);

				MomentsCircleListBean bean = MomentsCircleListBean
						.explainJson(content, VideoPlayerActivity.this);

				if(bean.type == 1) {
					showCircleListDialog(bean.getCircleList());
				}
				else {
					UIHelper.showToast(bean.msg);
				}

			}
		});
	}

	/**
	 * 选择圈子列表对话框
	 */
	private void showCircleListDialog(ArrayList<MomentsCircleItem> circleList) {
		MomentsCircleListDialog mCircleListDialog = new MomentsCircleListDialog(this, circleList, selectCircleId, new SelectCircleListener() {

			@Override
			public void onSelect(MomentsCircleItem circleItem) {
				try {
					showCircleInfo(circleItem);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
		mCircleListDialog.show();
	}

	/**
	 * 显示选择的圈子信息
	 */
	private void showCircleInfo(MomentsCircleItem circleItem) {
		mSelectCircleTv.setText(circleItem.getNAME());
		selectCircleId = circleItem.getID();
	}
	
	/**
	 * 检验是否符合发布条件
	 * @return
	 */
	private boolean check() {
		
		String titleStr = mTitleEdt.getText().toString().trim();
		String contentStr = mContentEdt.getText().toString().trim();
		
		if(TextUtils.isEmpty(titleStr)) {
			UIHelper.showToast("请输入标题");
			return false;
		}
		
		if(titleStr.length() < 5 || titleStr.length() > 20) {
			UIHelper.showToast("输入的标题在5到20字范围");
			return false;
		}
		
		if(TextUtils.isEmpty(contentStr)) {
			UIHelper.showToast("请输入您要分享的内容");
			return false;
		}
		
		if(contentStr.length() < 8 || contentStr.length() > 1000) {
			UIHelper.showToast("分享的内容在8到1000字范围");
			return false;
		}
		
		if (StringUtils.isEmpty(selectCircleId)) {
			UIHelper.showToast("请选择您要发布的圈子");
			return false;
		}
		
		return true;
	}
}
